package com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.repository.HddcStratigraphy25linepreNativeRepository;
import com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.repository.HddcStratigraphy25linepreRepository;
import com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.repository.entity.HddcStratigraphy25linepreEntity;
import com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.service.HddcStratigraphy25linepreService;
import com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.viewobjects.HddcStratigraphy25linepreQueryParams;
import com.css.zfzx.sjcj.modules.hddcStratigraphy25LinePre.viewobjects.HddcStratigraphy25linepreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcStratigraphy25linepreServiceImpl implements HddcStratigraphy25linepreService {

	@Autowired
    private HddcStratigraphy25linepreRepository hddcStratigraphy25linepreRepository;
    @Autowired
    private HddcStratigraphy25linepreNativeRepository hddcStratigraphy25linepreNativeRepository;

    @Override
    public JSONObject queryHddcStratigraphy25linepres(HddcStratigraphy25linepreQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcStratigraphy25linepreEntity> hddcStratigraphy25lineprePage = this.hddcStratigraphy25linepreNativeRepository.queryHddcStratigraphy25linepres(queryParams, curPage, pageSize, sort, order);
        List<HddcStratigraphy25linepreVO> hddcStratigraphy25linepreVOList = new ArrayList<>();
        List<HddcStratigraphy25linepreEntity> hddcStratigraphy25linepreEntityList = hddcStratigraphy25lineprePage.getContent();
        for(HddcStratigraphy25linepreEntity hddcStratigraphy25linepreEntity : hddcStratigraphy25linepreEntityList){
            HddcStratigraphy25linepreVO hddcStratigraphy25linepreVO = new HddcStratigraphy25linepreVO();
            BeanUtils.copyProperties(hddcStratigraphy25linepreEntity, hddcStratigraphy25linepreVO);
            if(PlatformObjectUtils.isNotEmpty(hddcStratigraphy25linepreEntity.getGeologyboundaryline())) {
                hddcStratigraphy25linepreVO.setGeologyboundarylineName(findByDictCodeAndDictItemCode("StraTouchTypeCVD", String.valueOf(hddcStratigraphy25linepreEntity.getGeologyboundaryline())));
            }
            hddcStratigraphy25linepreVOList.add(hddcStratigraphy25linepreVO);
        }
        Page<HddcStratigraphy25linepreVO> HddcStratigraphy25linepreVOPage = new PageImpl(hddcStratigraphy25linepreVOList, hddcStratigraphy25lineprePage.getPageable(), hddcStratigraphy25lineprePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(HddcStratigraphy25linepreVOPage);
        return jsonObject;
    }


    @Override
    public HddcStratigraphy25linepreEntity getHddcStratigraphy25linepre(String id) {
        HddcStratigraphy25linepreEntity hddcStratigraphy25linepre = this.hddcStratigraphy25linepreRepository.findById(id).orElse(null);
         return hddcStratigraphy25linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStratigraphy25linepreEntity saveHddcStratigraphy25linepre(HddcStratigraphy25linepreEntity hddcStratigraphy25linepre) {
        String uuid = UUIDGenerator.getUUID();
        hddcStratigraphy25linepre.setUuid(uuid);
        hddcStratigraphy25linepre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcStratigraphy25linepre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcStratigraphy25linepre.setIsValid("1");
        hddcStratigraphy25linepre.setQualityinspectionStatus("0");
        hddcStratigraphy25linepre.setExtends10("1");
        this.hddcStratigraphy25linepreRepository.save(hddcStratigraphy25linepre);
        return hddcStratigraphy25linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcStratigraphy25linepreEntity> saveHddcStratigraphy25linepreList(List<HddcStratigraphy25linepreEntity> list) {
        for (HddcStratigraphy25linepreEntity hddcStratigraphy25linepre : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcStratigraphy25linepre.setUuid(uuid);
            hddcStratigraphy25linepre.setCreateUser(PlatformSessionUtils.getUserId());
            hddcStratigraphy25linepre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcStratigraphy25linepre.setIsValid("1");
            hddcStratigraphy25linepre.setQualityinspectionStatus("0");
            hddcStratigraphy25linepre.setExtends10("1");
        }

        return hddcStratigraphy25linepreNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStratigraphy25linepreEntity updateHddcStratigraphy25linepre(HddcStratigraphy25linepreEntity hddcStratigraphy25linepre) {
        HddcStratigraphy25linepreEntity entity = hddcStratigraphy25linepreRepository.findById(hddcStratigraphy25linepre.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcStratigraphy25linepre);
        hddcStratigraphy25linepre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcStratigraphy25linepre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcStratigraphy25linepreRepository.save(hddcStratigraphy25linepre);
        return hddcStratigraphy25linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcStratigraphy25linepres(List<String> ids) {
        List<HddcStratigraphy25linepreEntity> hddcStratigraphy25linepreList = this.hddcStratigraphy25linepreRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcStratigraphy25linepreList) && hddcStratigraphy25linepreList.size() > 0) {
            for(HddcStratigraphy25linepreEntity hddcStratigraphy25linepre : hddcStratigraphy25linepreList) {
                hddcStratigraphy25linepre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStratigraphy25linepre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStratigraphy25linepre.setIsValid("0");
                this.hddcStratigraphy25linepreRepository.save(hddcStratigraphy25linepre);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcStratigraphy25linepreEntity> hddcStratigraphy25linepreList = this.hddcStratigraphy25linepreRepository.queryHddcStratigraphy25linepresByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcStratigraphy25linepreList) && hddcStratigraphy25linepreList.size() > 0) {
            for(HddcStratigraphy25linepreEntity hddcStratigraphy25linepre : hddcStratigraphy25linepreList) {
                hddcStratigraphy25linepre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStratigraphy25linepre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStratigraphy25linepre.setIsValid("0");
                this.hddcStratigraphy25linepreRepository.save(hddcStratigraphy25linepre);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcStratigraphy25linepreEntity> hddcStratigraphy25linepreList = this.hddcStratigraphy25linepreRepository.queryHddcStratigraphy25linepresByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcStratigraphy25linepreList) && hddcStratigraphy25linepreList.size() > 0) {
            for(HddcStratigraphy25linepreEntity hddcStratigraphy25linepre : hddcStratigraphy25linepreList) {
                hddcStratigraphy25linepre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStratigraphy25linepre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStratigraphy25linepre.setIsValid("0");
                this.hddcStratigraphy25linepreRepository.save(hddcStratigraphy25linepre);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("GeologyBoundaryLine")){
            str+="GeologyBoundaryLine,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveStratigraphy25linepreServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcStratigraphy25linepreEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcStratigraphy25linepreEntity data = new HddcStratigraphy25linepreEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeologyboundaryline(Integer.valueOf(obs.get(2).toString()));
                data.setCommentInfo(obs.get(3).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcStratigraphy25linepreList(datas);
        }
    }

    @Override
    public List<HddcStratigraphy25linepreEntity> findAll() {
        List<HddcStratigraphy25linepreEntity> list=this.hddcStratigraphy25linepreRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {

        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcStratigraphy25linepreRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcStratigraphy25linepreEntity> hddcStratigraphy25linepreList = this.hddcStratigraphy25linepreRepository.queryHddcStratigraphy25linepresByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcStratigraphy25linepreList) && hddcStratigraphy25linepreList.size() > 0) {
            hddcStratigraphy25linepreRepository.deleteAll(hddcStratigraphy25linepreList);
        }
    }


    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }


    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public void exportFile(HddcStratigraphy25linepreQueryParams queryParams, HttpServletResponse response) {
        List<HddcStratigraphy25linepreEntity> yhDisasterEntities = hddcStratigraphy25linepreNativeRepository.exportYhDisasters(queryParams);
        List<HddcStratigraphy25linepreVO> list=new ArrayList<>();
        for (HddcStratigraphy25linepreEntity entity:yhDisasterEntities) {
            HddcStratigraphy25linepreVO yhDisasterVO=new HddcStratigraphy25linepreVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"1：25万底图地层线-线","1：25万底图地层线-线",HddcStratigraphy25linepreVO.class,"1：25万底图地层线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcStratigraphy25linepreVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcStratigraphy25linepreVO.class, params);
            List<HddcStratigraphy25linepreVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcStratigraphy25linepreVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcStratigraphy25linepreVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcStratigraphy25linepreVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcStratigraphy25linepreEntity yhDisasterEntity = new HddcStratigraphy25linepreEntity();
            HddcStratigraphy25linepreVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcStratigraphy25linepre(yhDisasterEntity);
        }
    }
}
